package com.zzzy.sys.controller;

import com.zzzy.framework.common.annotation.RepeatSubmit;
import com.zzzy.sys.common.enums.GenderEnum;
import com.zzzy.framework.common.enums.sys.UserStatusEnum;
import com.zzzy.common.util.ExcelUtils;
import com.zzzy.sys.dao.entity.User;
import com.zzzy.sys.service.UserManageService;
import com.zzzy.sys.vo.usermanage.*;
import com.zzzy.common.vo.AjaxResult;
import com.zzzy.common.vo.PageResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Tag(name = "用户管理", description = "sys000")
@RestController
@Validated
@RequestMapping("/system/userManage")
public class UserManageController {

    @Resource
    private UserManageService userManageService;

    @Operation(summary = "用户列表")
    @GetMapping("/page")
    @PreAuthorize("@pvs.hasPermission('system:userManage:page')")
    public AjaxResult<PageResult<User>> page(@Valid @ParameterObject UserPageReq queryReq) {
        PageResult<User> userPage = userManageService.getUserPage(queryReq);
        return AjaxResult.success(userPage);
    }

    @RepeatSubmit
    @Operation(summary = "添加用户")
    @PostMapping("/add")
    @PreAuthorize("@pvs.hasPermission('system:userManage:add')")
    public AjaxResult add(@Valid @RequestBody UserAddReq userAddReq) {
        userManageService.add(userAddReq);
        return AjaxResult.success();
    }

    @GetMapping(value = {"/getUser/{id}"})
    @Operation(summary = "获得用户信息")
    @Parameter(name = "id", description = "用户ID", required = true)
    @PreAuthorize("@pvs.hasPermission('system:userManage:getUser')")
    public AjaxResult<UserUpdateInfoRes> getUser(@NotNull(message = "用户ID不能为空") @PathVariable("id") Long id) {
        UserUpdateInfoRes user = userManageService.getUserUpdateInfoResById(id);
        return AjaxResult.success(user);
    }

    @PutMapping("/update")
    @Operation(summary = "修改用户")
    @PreAuthorize("@pvs.hasPermission('system:userManage:update')")
    public AjaxResult update(@Valid @RequestBody UserUpdateReq updateReq) {
        userManageService.updateById(updateReq);
        return AjaxResult.success();
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除用户")
    @Parameter(name = "id", description = "用户ID", required = true)
    @PreAuthorize("@pvs.hasPermission('system:userManage:delete')")
    public AjaxResult delete(@NotNull(message = "用户ID不能为空") @PathVariable("id") Long id) {
        userManageService.deleteById(id);
        return AjaxResult.success();
    }

    @PutMapping("/resetPwd/{id}")
    @PreAuthorize("@pvs.hasPermission('system:userManage:resetPwd')")
    @Operation(summary = "重置密码,重置后密码为111111")
    @Parameter(name = "id", description = "用户ID", required = true)
    public AjaxResult resetPwd(@NotNull(message = "用户ID不能为空") @PathVariable("id") Long id) {
        userManageService.resetPwd(id);
        return AjaxResult.success();
    }

    @PutMapping("/unlock/{id}")
    @PreAuthorize("@pvs.hasPermission('system:userManage:unlock')")
    @Operation(summary = "用户解锁")
    @Parameter(name = "id", description = "用户ID", required = true)
    public AjaxResult unlock(@NotNull(message = "用户ID不能为空") @PathVariable("id") Long id) {
        userManageService.unlock(id);
        return AjaxResult.success();
    }

    @GetMapping("/getImportTemplate")
    @Operation(summary = "获得导入用户模板")
    public void getImportTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo
        List<UserImportExcelVO> list = Arrays.asList(
                UserImportExcelVO.builder().username("cs01").deptName("测试部门01").email("222222@qq.com").phoneNumber("13333333333")
                        .nickName("测试01").status(UserStatusEnum.CREATE.getValue()).sex(GenderEnum.MAN.getValue()).build(),
                UserImportExcelVO.builder().username("cs02").deptName("测试部门02").email("333333@qq.com").phoneNumber("13944444444")
                        .nickName("测试02").status(UserStatusEnum.ENABLE.getValue()).sex(GenderEnum.WOMAN.getValue()).build()
        );
        ExcelUtils.write(response, "用户导入模板.xls", "用户列表", UserImportExcelVO.class, list);
    }

    @PostMapping("/importExcel")
    @Operation(summary = "导入用户")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true")
    })
    @PreAuthorize("@pvs.hasPermission('system:userManage:importExcel')")
    public AjaxResult<UserImportExcelRes> importExcel(@RequestParam("file") MultipartFile file,
                                  @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
        List<UserImportExcelVO> list = ExcelUtils.read(file, UserImportExcelVO.class);
        return AjaxResult.success(userManageService.importUserList(list, updateSupport));
    }
}
